package net.zdreamer.geracomium.utils.file;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.content.Context;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Environment;
import android.widget.Toast;

public class getAdress {

	File sdcard = Environment.getExternalStorageDirectory();
	static String filePath = "/data/data/com.main.jh/addressinformation.db";
	static String pathStr = "/data/data/com.main.jh";

	SQLiteDatabase db;

	public SQLiteDatabase openDatabase(Context context) {

		File jhPath = new File(sdcard, filePath);
		getDataDir();
		AssetManager am = context.getAssets();
		InputStream is;
		try {
			is = am.open("addressinformation.db");
			FileOutputStream fos;
			fos = new FileOutputStream(
					Environment.getExternalStorageDirectory() + pathStr
							+ "/addressinformation.db");
			byte[] buffer = new byte[1024];
			int count = 0;
			while ((count = is.read(buffer)) > 0) {
				fos.write(buffer, 0, count);
				fos.flush();
			}
			fos.close();
			is.close();
			return SQLiteDatabase.openOrCreateDatabase(
					Environment.getExternalStorageDirectory() + pathStr
							+ "/addressinformation.db", null);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	public static File getDataDir() {
		File sdcard = Environment.getExternalStorageDirectory();

		if (sdcard == null || !sdcard.isDirectory()) {
			System.out.println("Storage card not found ");
			return null;
		}
		File dataDir = new File(sdcard, pathStr);
		if (!confirmDir(dataDir)) {
			System.out.println("Unable to create ");
			return null;
		}
		File data = new File(sdcard, filePath);
		try {
			data.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return dataDir;
	}

	private static boolean confirmDir(File dir) {
		if (dir.isDirectory())
			return true;
		if (dir.exists())
			return false;
		return dir.mkdirs();
	}

}
